import { ActivatedRoute } from '@angular/router';
import { Component, OnInit } from '@angular/core';
import { PopoverController } from '@ionic/angular';

import { pb } from 'src/pb';
import { FileService } from '../services/file.service';
import { PopoverItem } from '../dialog/popover-options';
import { SettingsService } from '../services/settings.service';
import { PopoverComponent } from '../dialog/popover/popover.component';

@Component({
  selector: 'app-folder',
  templateUrl: './folder.page.html',
  styleUrls: ['./folder.page.scss'],
})
export class FolderPage implements OnInit {

  folder: pb.IFolder;
  constructor(
    public ss: SettingsService,
    private activatedRoute: ActivatedRoute,
    private popoverCtrl: PopoverController,
    private fs: FileService,
  ) { }

  async ngOnInit() {
    const id = this.activatedRoute.snapshot.paramMap.get('id');
    this.folder = await this.fs.folder(id);
  }

  async openMenu(event: Event) {
    const items: PopoverItem[] = [
      {
        label: '文件尺寸',
        code: 'size',
        checked: this.ss.settings.showSize,
      },
      {
        label: '修改时间',
        code: 'date',
        checked: this.ss.settings.showDate,
      },
    ];
    const popover = await this.popoverCtrl.create({
      component: PopoverComponent,
      event,
      translucent: true,
      componentProps: {
        options: {
          title: '目录显示设置',
          items,
        }
      },
    });
    await popover.present();

    const r = await popover.onDidDismiss();

    if (r && r.data) {
      const item = items.find(i => i.code === r.data);
      if (item) {
        item.checked = !item.checked;
        if (item.code === 'size') {
          this.ss.settings.showSize = item.checked;
        }
        if (item.code === 'date') {
          this.ss.settings.showDate = item.checked;
        }
        this.ss.save();
      }
    }
  }

  async loadData(event) {
    event.target.disabled = !this.folder.next;
    if (this.folder.next) {
      const f = await this.fs.folder(this.folder.id, this.folder.files.length);
      this.folder.next = f.next;
      this.folder.files.push(...f.files);
      event.target.complete();
    }
  }
}
